package org.itboys.mobile.service.mysql.weixin;


import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.pay.SundayPayConfigMapper;
import org.itboys.mobile.dao.pay.SundayPayProductMapper;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.pay.SundayPay;
import org.itboys.mobile.entity.mysql.pay.SundayPayConfig;
import org.itboys.mobile.entity.mysql.pay.SundayPayProduct;
import org.itboys.mobile.service.mongo.weixin.SundayWeiXinMemberService;
import org.itboys.mobile.service.mysql.web.pay.SundayPayConfigService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.pay.alipay.AlipayMobileService;
import org.itboys.pay.alipay.AlipayWapResult;
import org.itboys.pay.tools.XMLUtil;
import org.itboys.pay.weixin.JsPaySignTool;
import org.itboys.pay.weixin.WXPayNotify;
import org.itboys.pay.weixin.WeixinPayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.DataInputStream;
import java.math.BigDecimal;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2016年6月22日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_支付_service_微信端。
 */
@Service
public class SundayWeiXinPayService extends BaseMySqlService<SundayPay> {
	protected  Logger logger = LoggerFactory.getLogger(getClass());

	public static String PAY_CALLBACK_STATUS_SUCCESS= "SUCCESS";
	//public static String PAY_CALLBACK_URL_alipay= "http://admin.isouniao.com/sunday/weixin/pay/callback/alipay";
	public static String PAY_CALLBACK_URL_wechat= "http://admin.qre.com.cn/sunday/weixin/pay/callback/wechat";

	/*	@Autowired
	private SundayWeiXinPayConfigService orderMapper;*/
	@Autowired
	private SundayPayConfigMapper payConfigMapper;
	@Autowired
	private SundayWeiXinMemberService memberService;
	@Autowired
	private SundayPayProductMapper payProductMapper;


	//进入支付页面，保存本地信息




	/**
	 *
	 * @param request
	 * @param memberId 用户ID
	 * @param productId 产品ID
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public JsPaySignTool preparePay(HttpServletRequest request, long memberId,long productId) throws Exception{
		if(!LongUtil.isNotZreo(memberId)){
			logger.error("用户信息已失效");
			throw new ErrorException("用户信息已失效");
		}
		Map<String,Object> param = new HashMap<String,Object>();
		//获取微信配置参数
		SundayPayConfig payConfig =null;
		param.put("type",SundayCommonConstants.pay_type_wechatpay_html);
		List<SundayPayConfig> payConfigs =payConfigMapper.select(param);

		if(ListUtil.isNull(payConfigs)){
			throw new ErrorException("预支付失败，微信未配置支付信息");
		}else{
			payConfig=payConfigs.get(0);
		}
		//支付的产品
		SundayPayProduct payProduct=payProductMapper.find(productId);
		BigDecimal payAmount=payProduct.getAmount();
		//第三方支付外部订单号
		String outTradeNo= NumberUtil.generateNumber("PREPAY");
		//获取用户的openId
		SundayMember member = memberService.getById(AccountIdHoldUtils.getSessionMember(request).getId());

		//微信支付的金额单位是分。
		String payAmountStr=String.valueOf(new BigDecimal(payAmount.doubleValue()*100).setScale(0,BigDecimal.ROUND_HALF_UP));
		//生成本地支付信息
		SundayPay sundayPay = new SundayPay(outTradeNo,String.valueOf(member.getId()),
				payAmount.setScale(2,BigDecimal.ROUND_HALF_UP), payProduct.getType(),"众包科技-用户升级");
		//HaoYiPay orderPay =new HaoYiPay(orderNo, orderIds,"搜鸟私厨-在线预定消费");
		super.insert(sundayPay);
		//统一下单
		JsPaySignTool tool=	WeixinPayUtils.jsPay(
				payConfig.getWeChatAppId(),
				payConfig.getWeChatMchId(),
				member.getWeixinOpenId(),
				outTradeNo, 	"202.101.164.136",
				sundayPay.getRemark(), payAmountStr,PAY_CALLBACK_URL_wechat, payConfig.getWeChatApi());
		return tool;
	}
	
	
	
	//微信回掉接口
	public String callback_wechat(HttpServletRequest request) throws Exception{
			Map<String,Object> param = new HashMap<String,Object>();
			//AlipayWapResult alipayWapResult=new AlipayWapResult();

			String callback_wechat_msg="success";
			//1，检验签名和请求来源
			DataInputStream in = new DataInputStream(request.getInputStream());
			byte[] dataOrigin = new byte[request.getContentLength()];
			in.readFully(dataOrigin); // 根据长度，将消息实体的内容读入字节数组dataOrigin中
			if(null != in){
				in.close(); // 关闭数据流
			}
			String wxNotifyXml = new String(dataOrigin);
			Map<String, String> params = XMLUtil.doXMLParse(wxNotifyXml);
			logger.info("00000---------callback_wechat--------开始-----");
			for (String key : params.keySet()) {
				logger.info("------微信html回掉返回的参数key = " + key + " and ---------value = " + params.get(key));
			}
			logger.info("00000---------callback_wechat--------结束-----");
			//
			//微信配置信息
			//获取微信配置参数
			SundayPayConfig payConfig =null;
			param.put("type",SundayCommonConstants.pay_type_wechatpay_html);
			List<SundayPayConfig> payConfigs =payConfigMapper.select(param);

			if(ListUtil.isNull(payConfigs)){
				return "fail";
			}else{
				payConfig=payConfigs.get(0);
			}
			//微信API
			String wechatApi = payConfig.getWeChatApi();
			//校验签名
			boolean isSign= WXPayNotify.verifyNotify(params,wechatApi);
			logger.info("-------------------微信-html-回掉-签名校验实际结果--"+isSign);
			//2017年6月14日，零时不校验签名
			//isSign=true;
			if(!isSign){
				logger.error("支付微信-html-回掉-签名验证失败。");
				return "fail";
			}


			String  trade_status=params.get("result_code");
			String  out_trade_no=params.get("out_trade_no");
			String trade_no = params.get("transaction_id");

			//微信返回的是分(金融单位)
			String  total_fee =params.get("total_fee");
			logger.info("支付-微信-html-回掉-信息.trade_status="+trade_status+
					",out_trade_no="+out_trade_no+
					",trade_no="+trade_no+
					",total_fee="+total_fee
			);

			//查询本地预支付记录
			param.clear();
			if(StringUtils.isEmpty(out_trade_no)){
				logger.error("支付-微信-html-回掉-外部订单为空");
				return "fail";
			}
			param.put("orderNo",out_trade_no);
			List<SundayPay> sundayPays = super.select(param);
			if(ListUtil.isNull(sundayPays)){
				logger.error("支付-微信-html-回掉-本地无预支付记录，返回");
				return "fail";
			}
			SundayPay pay=sundayPays.get(0);
			//2，项目内部逻辑。校验支付金额
			//校验付款金额。微信返回的是分（金额单位）
			BigDecimal paidAmount=new BigDecimal(Double.valueOf(total_fee)/100).setScale(2,BigDecimal.ROUND_HALF_UP);



			/*List<Long> orderIds = new ArrayList<Long>();
			for(String orderIdStr:pay.getOrderIds().split("_")){
				orderIds.add(Long.valueOf(orderIdStr));
			}*/
			if(StringUtils.isEmpty(pay.getOrderIds())){
				logger.error("支付-微信-回掉-本地预支付记录无用户参数，返回");
				return "fail";
			}
			param.clear();
			//1.0,校验预支付的订单金额是否和本次支付相同
			Double sundayPayAmount=0.00;
			for(SundayPay sundayPay:sundayPays){
				sundayPayAmount+=sundayPay.getPayAmount().doubleValue();
			}
			if(paidAmount.compareTo(new BigDecimal(sundayPayAmount).setScale(2,BigDecimal.ROUND_HALF_UP))==-1){
				logger.error("支付-微信-回掉-本地预支付金额和实际回掉金额有误-此操作标识有人非法刷单，本地预支付金额="+sundayPayAmount+",微信回掉金额="+paidAmount);
				return "fail";
			}

			//3.0修改用户类型状态
		//SundayMember member = memberService.getById(Long.valueOf(pay.getOrderIds().toString()));
			//2018年1月15日，增加套餐截至日期
		long deadTime = 0;
		Calendar calendar= Calendar.getInstance();
		if(pay.getType()==3){
			calendar.add(Calendar.DAY_OF_YEAR,365);
			deadTime=calendar.getTimeInMillis();
		}else{
			calendar.add(Calendar.DAY_OF_YEAR,7);
			deadTime=calendar.getTimeInMillis();
		}
		SundayMember member = new SundayMember();
		member.setUserType(pay.getType());
		member.setDeadTime(deadTime);
		memberService.updateExceptEmpty(Long.valueOf(pay.getOrderIds().toString()),member);


			return callback_wechat_msg;
		}


}


